// src/pages/ToolKit/dbEnv.tsx
import React from "react";
import { Row, Button, message } from "antd";
import { 
  DatabaseOutlined
} from "@ant-design/icons";
import { useStore } from '../../stores';
import { observer } from "mobx-react-lite";
import * as styles from '../../assets/styles/toolkit/environment.module';
import DBConnEnv from '../../components/ToolKit/DBConnEnv'; // 引入新创建的组件
import DBConnShow from '../../components/ToolKit/DBConnShow';
import EnvironmentVarManager from '../../components/ToolKit/EnvVarManager'; // 引入环境变量组件

// 定义数据库配置类型
interface DbConfig {
  host: string;
  port: string;
  database: string;
  username: string;
  password: string;
}

const Environment: React.FC = observer(() => {
  const store = useStore();
  
  // 从store中获取数据库卡片状态和激活的标签页

  const activeTab = store.toolkit.activeEnvTab;

  const dbCards = store.toolkit.dbCards;

  // 删除数据库卡片
  const removeDbCard = (id: number) => {
    store.toolkit.removeDbCard(id);
  };

  // 更新数据库配置
  const handleFormChange = (id: number, field: string, value: string) => {
    store.toolkit.updateDbCardConfig(id, field, value);
  };

  // 检查是否为有效IP地址
  const isValidIP = (host: string): boolean => {
    const ipPattern = /^(\d{1,3}\.){3}\d{1,3}$/;
    if (!ipPattern.test(host)) return false;
    
    const parts = host.split('.');
    return parts.every(part => parseInt(part, 10) >= 0 && parseInt(part, 10) <= 255);
  };

  // 检查是否为有效域名
  const isValidDomain = (host: string): boolean => {
    const domainPattern = /^[a-zA-Z0-9][a-zA-Z0-9-]{1,61}[a-zA-Z0-9](?:\.[a-zA-Z]{2,})+$/;
    return domainPattern.test(host);
  };

  // 检查表单是否有效
  const isFormValid = (config: DbConfig): boolean => {
    const { host, database, username, password } = config;
    
    // 主机地址、数据库名、用户名、密码都必填
    if (!host || !database || !username || !password) {
      return false;
    }
    
    // 如果主机地址是IP，则端口必填
    if (isValidIP(host) && !config.port) {
      return false;
    }
    
    return true;
  };

  // 测试连接函数
  const testConnection = async (id: number) => {
    const card = dbCards.find(c => c.id === id);
    if (!card) return;
    
    if (!isFormValid(card.config)) {
      message.error('请填写所有必填字段');
      return;
    }
    
    try {
      // 模拟连接测试
      await new Promise(resolve => setTimeout(resolve, 1000));
      // 设置数据库卡片为已连接状态
      store.toolkit.setDbCardConnected(id, true);
      store.toolkit.setRefactoredDbConnected(true);
      // 连接成功后移除卡片
      store.toolkit.removeConnectedDbCard(id);
      message.success('数据库连接成功');
    } catch (error) {
      message.error('数据库连接失败');
    }
  };

  // 处理数据库名称保存
  const handleDbNameSave = (id: number, name: string) => {
    store.toolkit.updateDbCardName(id, name);
  };

  // 添加新的数据库卡片
  const addNewDbCard = () => {
    // 生成长度为4的随机字符串(0-9,a-z,A-Z)
    const characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    let randomString = '';
    for (let i = 0; i < 4; i++) {
      randomString += characters.charAt(Math.floor(Math.random() * characters.length));
    }
    
    const newCard = {
      id: Date.now(),
      name: `自定义数据库名称-${randomString}`,
      config: {
        host: "",
        port: "",
        database: "",
        username: "",
        password: ""
      },
      isConnected: false
    };
    store.toolkit.addDbCard(newCard);
  };

  return (
    <div>
      <div className={styles.header}>
        <div className={styles.headerContainer}>

            <div style={{ display: 'flex', width: '100%' }}>
              <div 
                style={{ 
                  flex: activeTab === 'db' ? 9 : 1, 
                  display: 'flex', 
                  justifyContent: 'flex-start', 
                  alignItems: 'center', 
                  position: 'relative',
                  backgroundColor: activeTab === 'db' ? '#096dd9' : '#8A92A3',
                  cursor: 'pointer',
                  // padding: '12px 0',
                  transition: 'all 0.3s ease'
                }}
                onClick={() => store.toolkit.setActiveEnvTab('db')}
                onMouseEnter={(e) => {
                  if (activeTab !== 'db') {
                    e.currentTarget.style.backgroundColor = '#8A92A3';
                  }
                }}
                onMouseLeave={(e) => {
                  if (activeTab !== 'db') {
                    e.currentTarget.style.backgroundColor = '#8A92A3';
                  }
                }}
              >
                <div className={styles.dbEnvTab} style={{ 
                  flex: 1, 
                  display: 'flex', 
                  justifyContent: 'center',
                  fontWeight: activeTab === 'db' ? 'bold' : 'normal'
                }}>
                  <DatabaseOutlined className={styles.icon} />
                  <span>数据库配置</span>
                </div>
              </div>
              <div 
                style={{ 
                  flex: activeTab === 'var' ? 9 : 1, 
                  display: 'flex', 
                  justifyContent: 'center', 
                  cursor: 'pointer',
                  backgroundColor: activeTab === 'var' ? '#096dd9' : '#B7B9BC',
                  padding: '12px 0',
                  transition: 'all 0.3s ease'
                }}
                onClick={() => store.toolkit.setActiveEnvTab('var')}
                onMouseEnter={(e) => {
                  if (activeTab !== 'var') {
                    e.currentTarget.style.backgroundColor = '#B7B9BC';
                  }
                }}
                onMouseLeave={(e) => {
                  if (activeTab !== 'var') {
                    e.currentTarget.style.backgroundColor = '#B7B9BC';
                  }
                }}
              >
                <div className={styles.dbVarTab} style={{
                  display: 'flex',
                  alignItems: 'center',
                  fontWeight: activeTab === 'var' ? 'bold' : 'normal'
                }}>
                  <DatabaseOutlined className={styles.icon} />
                  <span>环境变量管理</span>
                </div>
              </div>
            </div>
          </div>

      </div>

      {/* 根据activeTab状态渲染不同组件 */}
      {activeTab === 'db' ? (
        <>
           <DBConnShow/>
        <Row gutter={[24, 24]}>
          {dbCards.map(card => (
            <DBConnEnv
              key={card.id}
              card={card}
              onFormChange={handleFormChange}
              onRemoveCard={removeDbCard}
              onAddNewCard={addNewDbCard}
              onTestConnection={testConnection}
              onDbNameSave={handleDbNameSave}
              isValidIP={isValidIP}
              isFormValid={isFormValid}
            />
          ))}
        </Row>
        </>
     
      ) : (
        <EnvironmentVarManager />
      )}
    </div>
  );
});

export default Environment;